package com.manage.web.controller;

import com.manage.domain.Dept;
import com.manage.service.IDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("/dept")
public class DeptController {

    @Autowired
    private IDeptService deptService;

    @RequestMapping("/list.do")
    public String list(@RequestParam(required = false) String name, Model model) {
        List<Dept> depts = (name == null || name.isEmpty()) ? deptService.list() : deptService.listByName(name);
        model.addAttribute("name", name);
        model.addAttribute("list", depts);
        return "dept-list";
    }

    @RequestMapping("/add.do")
    public String add(Dept dept, Model model) {
        deptService.add(dept);
        return "redirect:/dept/list.do";
    }

    @RequestMapping("/update.do")
    public String update(Dept dept) {
        deptService.update(dept);
        return "redirect:/dept/list.do";
    }

    @RequestMapping("/delete.do")
    public String delete(@RequestParam Integer id, Model model) {
        try {
            deptService.delete(id);
            return "redirect:/dept/list.do";
        } catch (Exception e) {
            model.addAttribute("error", e.getMessage());
            return list(null, model);
        }
    }
}


